//
//  GYTaskViewController.m
//  LockManagement
//
//  Created by apple on 2018/7/21.
//  Copyright © 2018年 yunjiazhineng. All rights reserved.
//

#import "GYTaskViewController.h"
#import "GYTaskHeadView.h"
#import "GYTaskTableViewCell.h"
#import "GYTask.h"
#import "GYTaskDownloadAlertView.h"
#import "GYBleDataManager.h"
#import "GYBleOperationManager.h"
#import "GYSpeechSynthesizerTool.h"
#import "GYNetWorkTools.h"
#import "GYDateTools.h"
#import "AppDelegate.h"
#import "GYUploadLog.h"


@interface GYTaskViewController ()<UITableViewDelegate,UITableViewDataSource>

/** task 表格 */
@property (nonatomic, strong) UITableView *taskTableView;

/** 表格头视图 */
@property (nonatomic, strong) GYTaskHeadView *headView;

/** 任务数据 */
@property (nonatomic, strong) NSArray *taskLists;

/** 记录当前加载的任务类型 */
@property (nonatomic, strong) NSString *taskType;

/** 记录当前加载的任务状态 */
@property (nonatomic, strong) NSString *taskState;

/** 当前正在授权的model */
@property (nonatomic, strong) GYTask *currentTask;

/** 蓝牙对象 */
@property (nonatomic, strong) GYBleOperationManager *bleOperationManager;

/** 记录秘钥协商过程中的数据 */
@property (nonatomic, strong) NSData *currentData;

/** 记录协商出的秘钥 */
@property (nonatomic, strong) NSData *secret_key;

/** 缓存多次返回的数据 */
@property (nonatomic, strong) NSMutableData *cachesData;

/** 代表当前收数据超过20戒字节 */
@property (nonatomic, assign) BOOL  isCaches;

/** 代表时哪个命令 */
@property (nonatomic, assign) NSInteger cmd;

/** 下载View */
@property (nonatomic, strong) GYTaskDownloadAlertView *downlaodAlertView;

/** 当前锁具名称 */
@property (nonatomic, strong) NSString *lockName;

/** 显示下载进度的view */
@property (nonatomic, strong) UIView *DownloadProgressView;

/** 进度lable */
@property (nonatomic, strong) UILabel *progressLable;

/** 进度视图 */
@property (nonatomic, strong) UIProgressView *progressView;

/** 总进度 */
@property (nonatomic, strong) UILabel *sumProgressLable;

/** 记录已经下载完成的数量 */
@property (nonatomic, assign) int count;

/** 任务总数 */
@property (nonatomic, assign) int sumCount;
@end

@implementation GYTaskViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //1.初始化
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage:) name:BLEReceeiveMessage object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:BLEReceeiveMessage object:nil];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.taskTableView.frame = CGRectMake(0, 0, self.view.width, self.view.height);
    self.headView.frame = CGRectMake(0, 0, self.view.width, [self.headView ViewHeight]);
}

- (void)setupUI {
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.taskTableView];
    self.taskType = @"2";
    self.taskState = @"1";
    self.lockName = @"";
    
    //加载任务数据
    [self loadTaskData];
    
    self.taskTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadTaskData)];
}


/**
 收到蓝牙返回数据

 @param noti <#noti description#>
 */
- (void)receiveMessage:(NSNotification *)noti {
    //NSLog(@"receiveMessage===============%@",noti.object);
    
    //解析收到的数据
    NSData *messageData = noti.object;
    
    //1.首先判断是不是钥匙校时的消息
    NSData *headData = [messageData subdataWithRange:NSMakeRange(2, 1)];
    int length = [[GYBleDataManager convertDataToHexStr:headData] intValue];
    NSLog(@"length==================%d",length);
    if (length == 20) {
        self.isCaches = NO;
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"TTMJ_234" iv:nil error:nil];
        NSLog(@"decryptData   20=========%@",decryptData);
    }else if (length == 21) {
        self.isCaches = NO;
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"TTMJ_234" iv:nil error:nil];
        NSLog(@"decryptData   21=========%@",decryptData);
        //发送指令编号21
        NSData *data = [GYBleDataManager consultKeySecond:21 content:decryptData secret_key:@"TTMJ_234"];
        [self sendMessageData:data];
    }else if (length == 22) {
        self.isCaches = NO;
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"TTMJ_234" iv:nil error:nil];
        NSLog(@"decryptData  22=========%@",decryptData);
        
        //发送指令编号是22
        NSData *data = [GYBleDataManager consultKeySecond:22 content:decryptData secret_key:decryptData];
        [self sendMessageData:data];
        self.currentData = decryptData;
    }else if (length == 23) {
        //收到这个命令是协商秘钥的指令完成了   开始显示下载进度界面
        self.isCaches = NO;
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:self.currentData iv:nil error:nil];
        self.secret_key = decryptData;
        NSLog(@"最后解析出来的秘钥 23=========%@",decryptData);
        
        //发送指令编号是23
        NSData *data = [GYBleDataManager consultKeySecond:23 content:decryptData secret_key:decryptData];
        [self sendMessageData:data];
        
        //暂停100毫秒
        [NSThread sleepForTimeInterval:0.01];
        
        //开始发送开门关门指令
        NSArray *areas = [NSJSONSerialization JSONObjectWithData:[self.currentTask.areas dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
        
        //收到这个命令是协商秘钥的指令完成了   开始显示下载进度界面
        self.sumCount = areas.count;
        
        if ([self.currentTask.offineTime intValue] != 0) {
#warning  巡更命令有待完成
            //NSLog(@" ...=====%@",self.currentTask.offineTime);
            //1.首先要发送一个获取锁的信息
            NSData *getLockInfoData = [GYBleDataManager getLockInfomation];
            [self sendMessageData:getLockInfoData];
            
        }else {
            //2.发送开关锁的命令
            if (self.currentTask.taskType == 2) {
                NSLog(@"循环发送开锁指令...");
                for (NSDictionary *dic in areas) {
                    NSString *lockID = [dic objectForKey:@"lockID"];
                    NSData *openData = [GYBleDataManager openOrCloseTheDoor:lockID schoolBeginTime:self.currentTask.taskBegin schoolEndTime:self.currentTask.taskEnd schoolTime:self.currentTask.taskTime operationType:1 SecretKey:decryptData];
                    [self sendMessageData:openData];
                    [NSThread sleepForTimeInterval:0.3];
                }
            }else if (self.currentTask.taskType == 3) {
                NSLog(@"循环发送关锁指令...");
                for (NSDictionary *dic in areas) {
                    NSString *lockID = [dic objectForKey:@"lockID"];
                    NSData *closeData = [GYBleDataManager openOrCloseTheDoor:lockID schoolBeginTime:self.currentTask.taskBegin schoolEndTime:self.currentTask.taskEnd schoolTime:self.currentTask.taskTime operationType:2 SecretKey:decryptData];
                    [self sendMessageData:closeData];
                    [NSThread sleepForTimeInterval:0.3];
                }
            }
        }
    }else if (length == 3) {
        self.isCaches = NO;
        //代表收到的开关锁信息
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];
        int successed = [[GYBleDataManager convertDataToHexStr:contentData] intValue];
        GYSpeechSynthesizerTool *tools = [[GYSpeechSynthesizerTool alloc] init];
        if (successed == 1) {
            //改变下载进度显示
            self.count += 1;
            if (self.count == self.sumCount) {
                [SVProgressHUD showSuccessWithStatus:@"任务下载成功!"];
                [tools textToSpeechConversion:@"任务下载成功"];
                [self.DownloadProgressView removeFromSuperview];
                self.DownloadProgressView = nil;
            }else {
                self.progressView.progress = (self.count*1.0)/self.sumCount;
                self.progressLable.text = [NSString stringWithFormat:@"%     %d",self.progressView.progress*100];
                self.sumProgressLable.text = [NSString stringWithFormat:@"%d/%d",self.count,self.sumCount];
            }
            
            
            //[SVProgressHUD showSuccessWithStatus:@"任务下载成功!"];
            //[tools textToSpeechConversion:@"任务下载成功"];
        }else {
            [SVProgressHUD showSuccessWithStatus:@"任务下载失败!"];
            [tools textToSpeechConversion:@"任务下载失败"];
            
            //移除下载jinduview
            [self.DownloadProgressView removeFromSuperview];
            self.DownloadProgressView = nil;
        }
    }else if (length == 4) {
        NSLog(@"代表设备锁日志上传, 需要解析数据,然后上传日志");
        self.isCaches = YES;
        self.cmd = length;
    }else if (length == 1) {
        self.isCaches = YES;
        self.cmd = length;
        //接收到的锁具数据要 凭借
        NSLog(@"表示接收到获取锁具信息成功,然后开始发送授权命令");
    }else if (length == 5) {
        self.isCaches = NO;
        NSData *contentData = [messageData subdataWithRange:NSMakeRange(5, messageData.length-7)];//TTMJ_345
        NSLog(@"授权钥匙收到数据===========%@",contentData);
        NSData *dercreyData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"TTMJ_345" iv:nil error:nil];
        
        int successed = [[GYBleDataManager convertDataToHexStr:dercreyData] intValue];
        GYSpeechSynthesizerTool *tools = [[GYSpeechSynthesizerTool alloc] init];
        if (successed == 1) {
            [SVProgressHUD showSuccessWithStatus:@"授权钥匙成功!"];
            [tools textToSpeechConversion:@"授权钥匙成功"];
        }else {
            [SVProgressHUD showErrorWithStatus:@"授权钥匙失败!"];
            [tools textToSpeechConversion:@"授权钥匙失败"];
        }
        
    }
    
    //代表收到是锁设备上传日志  然后要上传要平台
    if (self.isCaches) {
        [self.cachesData appendData:messageData];
        if (self.cmd == 4) {
            NSLog(@"收到锁发来的 开锁日志============%@",self.cachesData);
            
            if (self.cachesData.length == 47) {
                NSLog(@"代表日志 接受完毕了...");
                NSData *contentData = [self.cachesData subdataWithRange:NSMakeRange(5, self.cachesData.length-7)];
                NSData *decryptData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"TTMJ_345" iv:nil error:nil];
                //日志编号
                NSData *logNumData = [decryptData subdataWithRange:NSMakeRange(0, 4)];
                NSLog(@"logNumData===========%@",logNumData);
                //日志时间
                NSData *logTimeData = [decryptData subdataWithRange:NSMakeRange(4, 14)];
                NSLog(@"logTimeData===========%@",logTimeData);
                //类型操作
                NSData *typeData = [decryptData subdataWithRange:NSMakeRange(18, 1)];
                NSLog(@"typeData===========%@",typeData);
                //操作结果
                NSData *resultData = [decryptData subdataWithRange:NSMakeRange(19, 1)];
                NSLog(@"resultData===========%@",resultData);
                //用户编号
                NSData *userData = [decryptData subdataWithRange:NSMakeRange(20, 4)];
                NSLog(@"userData===========%@",userData);
                //所识别号
                NSData *lockNumData = [decryptData subdataWithRange:NSMakeRange(24, decryptData.length-24)];
                NSLog(@"lockNumData===========%@",lockNumData);
                
                //这里要把开锁日志上传到平台上去
                NSString *IP = GETOBJ(@"IP")
                NSString *port = GETOBJ(@"port")
                
                //操作时间
                NSLog(@"time=================%@",[[NSString alloc] initWithData:logTimeData encoding:NSUTF8StringEncoding]);
                NSString *operaTime = [GYDateTools dateString:[[NSString alloc] initWithData:logTimeData encoding:NSUTF8StringEncoding] withDateFormatter:@"yyyyMMddHHmmss"];
                NSString *type = [NSString stringWithFormat:@"%d",[[GYBleDataManager convertDataToHexStr:typeData] intValue]];
                NSString *state = [NSString stringWithFormat:@"%d",[[GYBleDataManager convertDataToHexStr:resultData] intValue]];
                NSString *keyID = @"4";
                NSString *lockID = @"";
                
                Byte *lock = (Byte *)lockNumData.bytes;
                for (int i = 0; i<lockNumData.length; i++) {
                    if (i%2 != 0) {
                        lockID = [lockID stringByAppendingFormat:@"%d",lock[i]];
                        if (i != 7) {
                            lockID = [lockID stringByAppendingString:@"-"];
                        }
                    }
                }
                NSLog(@"lockID=========%@",lockID);
                //NSString *lockID = [NSString stringWithFormat:@"%d-%d-%d-%d",lock[2],lock[4],lock[6],lock[8]];
                
                AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                if (app.networkState == 1 || app.networkState == 2) {
                    [GYNetWorkTools requestLogWithURL:[NSString stringWithFormat:@"http://%@:%@/api/log",IP,port] logTime:operaTime logType:type keyID:keyID lockID:lockID logState:state success:^(NSDictionary *obj) {
                        NSLog(@"obj=============%@  msg===========%@",obj,[obj objectForKey:@"msg"]);
                        int state = [[obj objectForKey:@"state"] intValue];
                        if (state == 0) {
                            NSLog(@"上传开锁日志成功!");
                            //清空缓存数据
                            self.cachesData = nil;
                        }
                    } error:^(NSError *error) {
                        NSLog(@"error=============%@",error);
                    }];
                }else {
                    NSLog(@"设备处于一个没有网络状态...要保存数据 然后等待有网络的时候上传...");
                    self.cachesData = nil;
                    NSString *filePath = [NSString CachesDir:@"uploadLog.plist"];
                    //首先取得这个缓存的字典
                    NSMutableArray *cachesLogArray = [NSMutableArray arrayWithContentsOfFile:filePath];
                    if (cachesLogArray.count == 0) {
                        cachesLogArray = [NSMutableArray array];
                    }
                    GYUploadLog *uploadLog = [[GYUploadLog alloc] init];
                    uploadLog.logTime = operaTime;
                    uploadLog.logType = type;
                    uploadLog.logState = state;
                    uploadLog.keyID = keyID;
                    uploadLog.lockID = lockID;
                    uploadLog.logID = [[GYBleDataManager convertDataToHexStr:logNumData] intValue];
                    
                    NSData *logData = [NSKeyedArchiver archivedDataWithRootObject:uploadLog];
                    NSString *key = [NSString stringWithFormat:@"%d",[[GYBleDataManager convertDataToHexStr:logNumData] intValue]];
                    [cachesLogArray addObject:logData];
                    
                    [cachesLogArray writeToFile:filePath atomically:YES];
                }
                
                self.cachesData = nil;
            }
        }else if (self.cmd == 1) {
            NSLog(@"收到所有的锁具信息数据=========%@  =======%lu",self.cachesData,(unsigned long)self.cachesData.length);
            
            //拿到收到的锁的信息  然后去得锁的识别号 在发送授权指令
            //第二步 收到获取锁具信息成功之后 然后在发送授权指令
            
            if (self.cachesData.length == 39) {
                //1.获取链接蓝牙的mac地址
                NSString *periphrealName = self.bleOperationManager.periphreal.name;
                NSString *mac = [periphrealName substringWithRange:NSMakeRange(periphrealName.length-12, 12)];
                
                //2.获取锁具编号
                NSData *contentData = [self.cachesData subdataWithRange:NSMakeRange(5, self.cachesData.length-7)];
                NSData *derectyData = [contentData LBXCryptWithOp:LBXOperaton_Decrypt algorithm:LBXAlgorithm_DES optionMode:LBXOptionMode_ECB padding:LBXPaddingMode_Zero key:@"SDtt6789" iv:nil error:nil];
                NSData *lockData = [derectyData subdataWithRange:NSMakeRange(0, 16)];
//                Byte lock1[] = {0x8f,0x2e,0xab,0xab,0x55,0x36,0x1d,0xc3,0x38,0xfc,0xc5,0x8f,0xaa,0x9e,0x76,0x35};
//                NSMutableData *lockData = [NSMutableData dataWithBytes:lock1 length:16];
                NSLog(@"得到的锁具IDData =============%@",lockData);
                
                NSArray *areas = [NSJSONSerialization JSONObjectWithData:[self.currentTask.areas dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
                for (NSDictionary *dic in areas) {
                    //NSString *lockID = [dic objectForKey:@"lockID"];
                    NSData *autoKeyData = [GYBleDataManager autoKey:lockData schoolBeginTime:@"2016-09-01 10:10:10" schoolEndTime:@"2099-09-01 10:10:10" schoolTime:@"2016-09-01 10:10:10" operationType:1 mac:mac];
                    [self sendMessageData:autoKeyData];
                }
                
                self.cachesData = nil;
            }
        }
    }
}

- (void)loadTaskData {
    //keyID  是表示当前蓝牙连接设备的钥匙
    NSNumber *keyID = GETOBJ(@"keyID");
    NSLog(@"keyID==========%@",keyID);
    if (keyID == nil) {
        [SVProgressHUD showInfoWithStatus:@"用户不存在此钥匙,请先添加钥匙!"];
        return;
    }//[NSString stringWithFormat:@"%@",keyID]
    [GYTask getTakListsWithKeyID:[NSString stringWithFormat:@"%@",keyID] lockName:self.lockName taskType:self.taskType taskState:self.taskState success:^(NSArray *tasks) {
        [self.taskTableView.mj_header endRefreshing];
        self.taskLists = tasks;
        [self.taskTableView reloadData];
    } error:^(NSError *error) {
        
    }];
}

#pragma mark -- UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.taskLists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYTaskTableViewCell *cell = [GYTaskTableViewCell cellWithTableView:tableView];
    cell.taskModel = self.taskLists[indexPath.row];
    kWeakSelf(self)
    cell.downloadBtnClickCallBack = ^(GYTask *model){
        if (model.authName != nil && model.authName.length != 0 && ![model.authName isEqualToString:@""]) {
            //1.判断蓝牙是否连接  没有连接则直接返回
            if (weakself.bleOperationManager.connectType != deviceConntTypeSuccess) {
                GYSpeechSynthesizerTool *tools = [[GYSpeechSynthesizerTool alloc] init];
                [tools textToSpeechConversion:@"蓝牙未连接,请连接蓝牙后下载"];
                
                //1.1移除下载界面
                return;
            }
            
            NSLog(@"下载该任务...");
            GYTaskDownloadAlertView *downlaodAlertView = [GYTaskDownloadAlertView initWithFrame:[UIScreen mainScreen].bounds];
            downlaodAlertView.task = weakself.taskLists[indexPath.row];
            kWeakSelf(self)
            downlaodAlertView.sendAutoCommandCallBack = ^(GYTask *task){
            weakself.currentTask = task;
                
                //2.发送协商秘钥的指令
                NSData *data = [GYBleDataManager consultKey];
                [weakself sendMessageData:data];
                
                //3.这里需要添加下载进度视图
                weakself.count = 0;
                [weakself showDownloadProgressView:0];
                
                //4.搞一个定时器来检测下
                [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(timer:) userInfo:nil repeats:NO];
                
            };
            //weakself.downlaodAlertView = downlaodAlertView;
            
            [[[UIApplication sharedApplication] keyWindow] addSubview:downlaodAlertView];
            
        }else {
            NSLog(@"任务需要授权....");
            [model taskGive:^(BOOL successed) {
                if (successed) {
                    //刷新任务列表
                    [weakself loadTaskData];
                }
            } error:^(NSError *error) {
                
            }];
        }
    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    GYTaskTableViewCell *cell = [GYTaskTableViewCell cellWithTableView:tableView];
    
    return [cell cellHeight];
}

- (void)timer:(NSTimer *)sender {
    if (self.DownloadProgressView) {
        [self.DownloadProgressView removeFromSuperview];
        [SVProgressHUD showErrorWithStatus:@"下载任务失败!"];
    }
}

/**
 显示下载进度视图
 */
- (void)showDownloadProgressView:(int)sumTaskCount {
    //1.首先要移除下载
    UIView *DownloadProgressView = [[UIView alloc] initWithFrame:UIScreen.mainScreen.bounds];
    DownloadProgressView.backgroundColor = [UIColor colorWithWhite:0.4 alpha:0.4];
    
    //添加下载进度View
    UIView *progressView = [[UIView alloc] initWithFrame:CGRectMake(30, DownloadProgressView.height/2-60, DownloadProgressView.width-60, 120)];
    progressView.backgroundColor = UIColor.whiteColor;
    [DownloadProgressView addSubview:progressView];
    
    UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(20, 15, progressView.width-20, 30)];
    titleLable.text = @"任务下发";
    titleLable.textColor = BackGroundColor;
    titleLable.font = [UIFont systemFontOfSize:20];
    
    [progressView addSubview:titleLable];
    
    UILabel *markLbale = [[UILabel alloc] initWithFrame:CGRectMake(0, 59, progressView.width, 1)];
    markLbale.backgroundColor = BackGroundColor;
    [progressView addSubview:markLbale];
    
    UIProgressView *progress = [[UIProgressView alloc] initWithFrame:CGRectMake(10, 80, progressView.width-20, 2)];
    progress.progress = 0.0;
    [progressView addSubview:progress];
    
    UILabel *progressLable = [[UILabel alloc] initWithFrame:CGRectMake(10, 85, 50, 30)];
    progressLable.textColor = [UIColor blackColor];
    progressLable.text = @"0%";
    [progressView addSubview:progressLable];
    
    UILabel *sumLable = [[UILabel alloc] initWithFrame:CGRectMake(progressView.width-60, 85, 50, 30)];
    sumLable.textColor = [UIColor blackColor];
    sumLable.text = [NSString stringWithFormat:@"0/%d",sumTaskCount];//@"0/3";
    [progressView addSubview:sumLable];
    
    [[UIApplication sharedApplication].keyWindow addSubview:DownloadProgressView];
    kWeakSelf(self)
    weakself.DownloadProgressView = DownloadProgressView;
    weakself.progressLable = progressLable;
    weakself.progressView = progress;
    weakself.sumProgressLable = sumLable;
}

#pragma 蓝牙的发送数据 处理方法 --- 这个蓝牙收发最多只能20字节,超过20字节的需要自己分段  分成20字节一段开始发送

/**
 针对蓝牙发送的数据做一个分包处理
 
 @param messageData <#messageData description#>
 */
- (void)sendMessageData:(NSData *)messageData {
    if (messageData.length > 20) {
        NSData *contentData;
        int count = messageData.length/20 + 1;
        
        Byte *testByte =(Byte *)[messageData bytes];
        for (int i = 0; i < count; i++) {
            Byte ceshi[20] = {0};
            for (int k=0; k < 20; k++) {
                ceshi[k] = testByte[i*20+k];
            }
            NSData *ceshiData = [NSData dataWithBytes:ceshi length:20];
            [self.bleOperationManager sendMessage:ceshiData];
            [NSThread sleepForTimeInterval:0.01];
        }
    }else {
        [self.bleOperationManager sendMessage:messageData];
    }
}


#pragma mark -- 懒加载

- (UITableView *)taskTableView {
    if (!_taskTableView) {
        _taskTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _taskTableView.delegate = self;
        _taskTableView.dataSource = self;
        _taskTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        _taskTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, CGFLOAT_MIN)];
        //赋值头视图
        GYTaskHeadView *headView = [GYTaskHeadView shareView];
        headView.frame = CGRectMake(0, 0, self.view.width, [headView ViewHeight]);
        kWeakSelf(self)
        headView.updateTaskListToTaskTypeCallBack = ^(NSString *taskType) {
            weakself.taskType = taskType;
            
            //重新加载数据
            [weakself loadTaskData];
        };
        headView.updateTaskListToTaskStateCallBack = ^(NSString *taskState) {
            weakself.taskState = taskState;
            
            //重新加载数据
            [weakself loadTaskData];
        };
        
        headView.searchTaskCallBack = ^(NSString *searchText) {
            weakself.lockName = searchText;
            [weakself loadTaskData];
        };
        
        _taskTableView.tableHeaderView = headView;
        self.headView = headView;
    }
    
    return _taskTableView;
}

- (GYBleOperationManager *)bleOperationManager {
    if (!_bleOperationManager) {
        _bleOperationManager = [GYBleOperationManager shareOperationManager];
    }
    
    return _bleOperationManager;
}

- (NSMutableData *)cachesData {
    if (!_cachesData) {
        _cachesData = [NSMutableData data];
    }
    
    return _cachesData;
}












@end
